//===----------------------------------------------------------------------===//
// Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//===----------------------------------------------------------------------===//
module org.openapis.v3.tests.SchemaGenerator

amends "pkl:test"

import "fixtures/SelfReference.pkl"
import "../examples/SwallowSchema.pkl"
import "../SchemaGenerator.pkl"
import "../Schema.pkl"

local schema = SchemaGenerator.generate(SwallowSchema.Swallow)

facts {
  ["recursive references throw an error"] {
    module.catch(() -> SchemaGenerator.generate(SelfReference).output.text)
      .startsWith("Invalid Schema: Unable to convert a schema that refers to itself.")
  }
  ["nullable values show up as nullable"] {
    (schema.properties!!["airSpeed"] as Schema).nullable == true
  }
  ["deprecated fields show up as deprecated"] {
    (schema.properties!!["isDuck"] as Schema).deprecated == true
  }
  ["generates basic metadata"] {
    schema.title == "Swallow"
    schema.description == "This is a Swallow"
  }
  ["listings are encoded as arrays"] {
    local nicknameSchema = schema.properties!!["nicknames"] as Schema
    nicknameSchema.type == "array"
    nicknameSchema.items.type == "string"
  }
  ["mappings are encoded as objects"] {
    local tagsSchema = schema.properties!!["tags"] as Schema
    tagsSchema.type == "object"
    tagsSchema.additionalProperties.type == "string"
  }
  ["classes are encoded as objects"] {
    local friendSchema = schema.properties!!["bestFriend"] as Schema
    friendSchema.type == "object"
    friendSchema.properties.toMap().keys == Set("name", "isSwallow", "tags")
  }
}

examples {
  ["converts a module"] {
    let (schema = new SchemaGenerator {
      converters {
        [DataSize] {
          title = "DataSize"
          type = "string"
          description = "The size of data in [quantity][unit] representation."
        }
      }
    }.generate(SwallowSchema.Swallow))
      new JsonRenderer {}.renderDocument(schema)
  }
}
